﻿using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using SDS.SharePoint.ReplaceDocument.Utility;

namespace SDS.SharePoint.ReplaceDocument.Layouts.SDS.SharePoint.ReplaceDocument
{
    public partial class Replace : LayoutsPageBase
    {

        private string m_fileUrl;
        protected string CurrentFileUrl
        {
            get
            {
                if (String.IsNullOrEmpty(m_fileUrl))
                {
                    if (String.IsNullOrEmpty(this.Request.QueryString["File"]))
                        throw new SPException(SPResource.GetString("FileGone", new object[0]));

                    m_fileUrl = Request.QueryString["File"]
                                       .TrimStart(SPContext.Current.Web.Url)                      // convert Fully Qualified URL to SPWeb relative URL
                                       .TrimStart(SPContext.Current.Web.ServerRelativeUrl)        // convert server relative URL to SPWeb relative URL
                                       .TrimStart("/");                                           // remove the leading /
                }
                return m_fileUrl;
            }
        } // string CurrentFileUrl

        private SPFile m_file;
        protected SPFile CurrentFile
        {
            get
            {
                if (this.m_file == null)
                {

                    SPFile spFile = ((UnsecuredLayoutsPageBase)this).Web.GetFile(CurrentFileUrl) as SPFile;

                    if (spFile == null)
                        throw new SPException(SPResource.GetString("NotInDocLib", new object[0]));
                    if (!spFile.Exists)
                        throw new SPException(SPResource.GetString("FileGone", new object[0]));

                    this.m_file = spFile;
                }
                return this.m_file;
            }
        } // SPFile CurrentFile

        #region Borrowed from Microsoft.SharePoint.ApplicationPages.UploadPage

        private SPDocumentLibrary m_list;
        protected SPDocumentLibrary CurrentList
        {
            get
            {
                if (this.m_list == null)
                {
                    string WebRelativeListUrl = "/" + CurrentFileUrl.Remove(CurrentFileUrl.LastIndexOf('/'));
                    string ServerRelativeListUrl = SPContext.Current.Web.ServerRelativeUrl.TrimStart("/") + WebRelativeListUrl;
                    SPDocumentLibrary spDocumentLibrary = SPContext.Current.Web.GetList(ServerRelativeListUrl) as SPDocumentLibrary;
                    
                    if (spDocumentLibrary == null)
                        throw new SPException(SPResource.GetString("NotInDocLib", new object[0]));

                    this.m_list = spDocumentLibrary;
                }
                return this.m_list;
            }
        }

        protected bool IsSolutionCatalog
        {
            get
            {
                return ((SPList)this.CurrentList).BaseTemplate == SPListTemplateType.SolutionCatalog; //121;
            }
        }
        protected bool IsPictureLibrary
        {
            get
            {
                return ((SPList)this.CurrentList).BaseTemplate == SPListTemplateType.PictureLibrary; // 109;
            }
        }

        private static string GetLeafName(string s)
        {
            int num = s.LastIndexOf('\\');
            if (num >= 0)
                return s.Substring(num + 1);
            else
                return s;
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            ID_FileProperty.File = CurrentFile;
        }

        protected void ValidateFile(object source, ServerValidateEventArgs args)
        {
            CustomValidator customValidator = (CustomValidator)source;
            HtmlInputFile htmlInputFile = (HtmlInputFile)customValidator.FindControl(customValidator.ControlToValidate);

            args.IsValid = htmlInputFile.PostedFile != null && 
                           htmlInputFile.PostedFile.ContentLength > 0;
            //             && SPUrlUtility.IsLegalFileName(GetLeafName(htmlInputFile.PostedFile.FileName))      // not necessary... filename not used
        } // void ValidateFile(...)

        protected void ValidateFileExtension(object source, ServerValidateEventArgs args)
        {
            CustomValidator customValidator = (CustomValidator)source;
            HtmlInputFile htmlInputFile = (HtmlInputFile)customValidator.FindControl(customValidator.ControlToValidate);

            // file extension is just everything after the last .
            string CurrentFileExtension = this.CurrentFile.Name.Substring(this.CurrentFile.Name.LastIndexOf('.') + 1);
            string UploadFileExtension = htmlInputFile.PostedFile.FileName.Substring(htmlInputFile.PostedFile.FileName.LastIndexOf('.') + 1);

            // valid if the file extensions match
            args.IsValid = CurrentFileExtension == UploadFileExtension;
            if (!args.IsValid)
            {
                customValidator.ErrorMessage = String.Format("The type of file being uploaded ({1}) does not match the current file type ({0})", CurrentFileExtension, UploadFileExtension);
            }
        } // void ValidateFileExtension(...)


        protected virtual void OnSubmit(object o, EventArgs e)
        {
            ((Control)this).Page.Validate();
            if (!((Control)this).Page.IsValid)
                return;
            using (SPLongOperation longOperation = new SPLongOperation((Page)this))
            {
                longOperation.Begin();

                SPFile spFile = this.CurrentFile;
                spFile.SaveBinary(InputFile.PostedFile.InputStream);

                OnSubmit_EndLongOperation(longOperation);
            } // using LongOperation

        } // void OnSubmit(...)

        protected void OnSubmit_EndLongOperation(SPLongOperation operation)
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            if (context.Request.QueryString["IsDlg"] != null)
            {
                context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
                context.Response.Flush();
                context.Response.End();
            }
            else
            {
                if (context.Request.QueryString.AllKeys.Contains("Source"))
                {
                    // redirect back to source page
                    operation.End(context.Request.QueryString["Source"], SPRedirectFlags.CheckUrl, context, string.Empty);
                }
                else
                {
                    // close the window
                    operation.EndScript("window.close();");
                } // querystring.contains("Source")

            } // is modal dialog
        } // void OnSubmit_EndLongOperation(...)

    } // class
} // namespace
